package com.liyu.controller;

import cn.hutool.core.date.DateUtil;
import com.liyu.config.DelayedComment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;

/**
 * @author 李誉
 * @date 2022-07-17 15:30
 * @description
 */
@Slf4j
@RestController
@RequestMapping("delayed")
public class DelayedController {


    @Resource
    private RabbitTemplate rabbitTemplate;

    //依赖注入rabbitMQ之后再设置它的回调对象
    @PostConstruct
    public void init(){
//        rabbitTemplate.setConfirmCallback((@Nullable CorrelationData correlationData, boolean ack, @Nullable String cause) -> {
//            Message returnedMessage = correlationData.getReturnedMessage();
//            String msg = new String(correlationData.getReturnedMessage().getBody(),StandardCharsets.UTF_8);
//            log.info("消息发送成功，交换机：{}，路由：{}，时间：{}，消息：{}",
//                    correlationData.getReturnedMessage().getMessageProperties().getReceivedExchange(),
//                    correlationData.getReturnedMessage().getMessageProperties().getReceivedRoutingKey(),
//                    DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"),
//                    msg);
//        });
//        这里不打印发布异常确认，因为延迟插件是把消息放入内存等待，必然会报错
//        rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange, String routingKey) -> {
//            String msg = new String(message.getBody(), StandardCharsets.UTF_8);
//            log.warn("消息：{},被交换机:{}退回,退回原因:{},路由key:{}",msg,exchange,replyText,routingKey);
//        });
    }

    @GetMapping("{msg}/{delay}")
    public void send(@PathVariable("msg") String msg, @PathVariable(value = "delay", required = false) Integer delay) {
        delay = ObjectUtils.isEmpty(delay) ? 10000 : delay;
        Integer finalDelay = delay;
        rabbitTemplate.convertAndSend(DelayedComment.DELAYED_EXCHANGE, DelayedComment.DELAYED_ROUTING_KEY, msg, message -> {
            MessageProperties messageProperties = message.getMessageProperties();
            messageProperties.setDelay(finalDelay);
            return message;
        });
        log.info("消息发送成功，时间：{}，延迟：{}，消息：{}，交换机：{}，路由：{}",
                DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"),
                finalDelay,
                msg,
                DelayedComment.DELAYED_EXCHANGE,
                DelayedComment.DELAYED_EXCHANGE
        );
    }
}
